<script setup>
  import { accountListAccountByOrganizationPage } from '@/api/brac/account';
  import { NstdMessage } from 'nstd-components-pc-v3';
  import { useOrganizationTree } from '@/hooks/useOrganizationTree';
  import { isArray, isString } from '@/utils';
  const { data: treeData } = useOrganizationTree();
  const attrs = useAttrs();
  const emits = defineEmits(['confirm']);
  const props = defineProps({
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 组织机构id
    orgId: {
      type: String,
      default: ''
    },
    // 默认选中
    defaultSelected: {
      type: [String, Array],
      default: () => []
    }
  });
  const searchForm = reactive({
    orgId: props.orgId
  });
  const searchFormRef = ref();
  const treeProps = {
    label: 'orgName',
    children: 'children'
  };
  const actions = [
    {
      id: 'clear',
      text: '清空选择',
      iconName: 'button_delete'
    },
    {
      id: 'confirm',
      text: '确定',
      iconName: 'button_confirm'
    }
  ];
  const columns = [
    {
      label: '用户名称',
      prop: 'realName'
    },
    {
      label: '部门名称',
      prop: 'orgName'
    },
    {
      label: '岗位名称',
      prop: 'postStation'
    },
    {
      label: '角色名称',
      prop: 'roleName'
    },
    {
      label: '账号名称',
      prop: 'accountName'
    }
  ];
  const tableData = ref([]);
  const userTable = ref();
  const pagination = reactive({
    total: 0,
    'current-page': 1,
    'page-size': 30
  });
  const selectionList = computed(() => {
    return unref(userTable).selection;
  });
  // 表示是否已经获取到table数据,拿到数据之后需要执行一下默认勾选方法,并且只会执行一次
  const hasTableData = ref(false);
  const accountListAccountByOrganizationPageData = async () => {
    try {
      const params = Object.assign({}, searchForm, {
        pageSize: pagination['page-size'],
        pageNum: pagination['current-page']
      });
      const { code, data } = await accountListAccountByOrganizationPage(params);
      if (code === 200) {
        hasTableData.value = true;
        tableData.value = data.data;
        pagination.total = data.total;
      }
    } catch (error) {
      console.error(error, 'accountListAccountByOrganizationPage');
    }
  };

  watchEffect(() => {
    accountListAccountByOrganizationPageData();
  });
  watch(
    [() => attrs.modelValue, hasTableData],
    ([visible, hasTableData]) => {
      if (visible || hasTableData) {
        const selectRows = getSelectRows(props.defaultSelected);
        toggleSelect(selectRows);
      }
    },
    { immediate: true }
  );
  function getSelectRows(value) {
    const result = [];
    let idList;
    if (isArray(value)) {
      idList = [...value];
    }
    if (isString(value)) {
      idList = value.split(',');
    }
    idList.forEach((id) => {
      const row = tableData.value.find((item) => item.id === id);
      if (row) result.push(row);
    });
    return result;
  }
  function toggleSelect(selectRows) {
    // 没有默认选中的行 直接return
    if (selectRows.length < 1) return;
    // 每次设置默认勾选,都需要清空以前的勾选
    handleClear();
    nextTick(() => {
      selectRows.forEach((row) => {
        unref(userTable).tableRef.toggleRowSelection(row, true);
      });
    });
  }
  function handleClear() {
    unref(userTable)?.tableRef?.clearSelection();
  }
  function handleConfirm() {
    if (selectionList.value.length === 0) {
      return NstdMessage.warning('请至少选择一条数据');
    }
    // 单选只能选择一条数据
    if (!props.multiple && selectionList.value.length !== 1) {
      return NstdMessage.warning('只能选择一条数据');
    }
    console.log(selectionList, 'selectionList');
    // 所有的条件都满足才抛出confirm事件
    emits('confirm', unref(selectionList));
  }
  const actionMethodsMap = {
    query: handleQuery,
    reset: handleReset,
    clear: handleClear,
    confirm: handleConfirm
  };
  function handleQuery() {
    pagination['current-page'] = 1;
    accountListAccountByOrganizationPageData();
  }
  function handleReset() {
    console.log('reset');
    searchForm.orgId = '';
    unref(searchFormRef).resetFields();
    pagination['current-page'] = 1;
    accountListAccountByOrganizationPageData();
  }
  function handleActionClick(item) {
    console.log(item, 'item');
    actionMethodsMap[item.id]();
  }
  function handleNodeClick(node) {
    searchForm.orgId = node.id;
  }
  function handlePageChange(currentPage, pageSize) {
    pagination['current-page'] = currentPage;
    pagination['page-size'] = pageSize;
    accountListAccountByOrganizationPageData();
  }
  function handleSelectChange(_selection) {
    if (!props.multiple) {
      if (_selection.length > 1) {
        nextTick(() => {
          unref(userTable).tableRef.toggleRowSelection(_selection[0], false);
        });
      }
    }
  }
  function handleClose() {
    handleClear();
  }
  defineExpose({
    clear: handleClear
  });
</script>

<template>
  <NstdDialog title="选择人员" v-bind="attrs" width="1200" @close="handleClose">
    <div class="h-600px flex">
      <div class="w-200px">
        <NstdScrollbar>
          <NstdTree :data="treeData" :props="treeProps" @node-click="handleNodeClick" />
        </NstdScrollbar>
      </div>
      <div class="flex flex-col justify-between h-full flex-1 min-w-0">
        <NcTitle title="筛选条件" has-padding @action-click="handleActionClick">
          <NstdForm ref="searchFormRef" class="w-95%" :model="searchForm" inline label-width="80">
            <NstdRow :gutter="20">
              <NstdCol :span="8">
                <NstdFormItem label="用户名称" prop="realName">
                  <NstdInput v-model="searchForm.realName" />
                </NstdFormItem>
              </NstdCol>
            </NstdRow>
          </NstdForm>
        </NcTitle>
        <NcTitle class="flex-1 min-h-0" title="人员列表" :actions="actions" @action-click="handleActionClick">
          <NcTable
            ref="userTable"
            :columns="columns"
            :data="tableData"
            :pagination="pagination"
            @page-change="handlePageChange"
            @selection-change="handleSelectChange"
          />
        </NcTitle>
      </div>
    </div>
  </NstdDialog>
</template>

<style scoped lang="scss"></style>
